package com.xiaoshuidi.cloud.module.member.repository;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoshuidi.cloud.framework.web.core.util.WebFrameworkUtils;
import com.xiaoshuidi.cloud.module.member.controller.admin.coupon.vo.CouponCustomerPCForm;
import com.xiaoshuidi.cloud.module.member.enums.coupon.CouponTypeEnum;
import com.xiaoshuidi.cloud.module.member.mapper.coupon.CouponRecordMapper;
import com.xiaoshuidi.cloud.module.member.pojo.coupon.CouponEntity;
import com.xiaoshuidi.cloud.module.member.pojo.coupon.CouponRecordEntity;
import com.xiaoshuidi.cloud.module.system.api.user.AdminUserApi;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;


@Repository
@RequiredArgsConstructor
public class MemberCouponRecordRespository extends ServiceImpl<CouponRecordMapper, CouponRecordEntity> {
    private final CouponRecordMapper mapper;
    private final AdminUserApi adminUserApi;

    /**
     * 自动发送预定优惠券活动
     *
     * @param coupon
     * @param mobile
     * @param flag
     */
    public CouponRecordEntity sendCouponRecord(CouponEntity coupon, String mobile, Integer flag) {
        //组装发放记录
        CouponRecordEntity couponRecordEntity = new CouponRecordEntity();
        couponRecordEntity.setCouponId(coupon.getId());
        couponRecordEntity.setCouponName(coupon.getCouponName());
        //自动发放，无发放人
        couponRecordEntity.setIssuerAccount(mobile);
        couponRecordEntity.setIssuerNum(1L);
        if (flag.intValue() == CouponTypeEnum.OLD_WITH_NEW_DISCOUNT.getNum().intValue()) {
            couponRecordEntity.setRemarks("老带新自动发放优惠券");
        } else if (flag.intValue() == CouponTypeEnum.RESERVATION_DISCOUNT.getNum().intValue()) {
            couponRecordEntity.setRemarks("预定优惠券自动发放");
        } else if (flag.intValue() == CouponTypeEnum.NEW_SIGNING_DISCOUNT.getNum().intValue()) {
            couponRecordEntity.setRemarks("新签约优惠券自动发放");
        }
        mapper.insert(couponRecordEntity);
        return couponRecordEntity;
    }

    public CouponRecordEntity sendManualCouponRecord(CouponEntity coupon, CouponCustomerPCForm form) {
        //组装发放记录
        CouponRecordEntity couponRecordEntity = new CouponRecordEntity();
        couponRecordEntity.setCouponId(coupon.getId());
        couponRecordEntity.setCouponName(coupon.getCouponName());
        couponRecordEntity.setIssuerName(adminUserApi.getUser(WebFrameworkUtils.getLoginUserId()).getData().getNickname());
        couponRecordEntity.setIssuerAccount(form.getUserPhone());
        couponRecordEntity.setIssuerNum(form.getCouponNum());
        couponRecordEntity.setRemarks(form.getRemarks());
        couponRecordEntity.setCouponUrl(JSONObject.toJSONString(form.getCouponUrls()));
        mapper.insert(couponRecordEntity);
        return couponRecordEntity;
    }
}
